package wechat.base.snd.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.log4j.Logger;

@SuppressWarnings("all")
public class PostFile {
	static Logger log = Logger.getLogger(PostFile.class.getName());

	public static String uploadFile(String targetURL, String fileName, String type) {
		String ret = null;
		HttpClientBuilder httpclientBuilder = HttpClientBuilder.create();
		HttpClient httpclient = httpclientBuilder.build();
		targetURL = targetURL + "&type=" + type;
		HttpPost httppost = new HttpPost(targetURL);
		File file = new File(fileName);

		MultipartEntityBuilder httpEntity = MultipartEntityBuilder.create();
		httpEntity.addBinaryBody("media", file,
				ContentType.create("multipart/form-data", Consts.UTF_8),
				fileName);
		httppost.setEntity(httpEntity.build());

		try {
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity resEntity = response.getEntity();

			log.info("+++++++++++++++++++++++++++++");
			InputStream contentStream = resEntity.getContent();
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[WeChatConf.WECHAT_URL_RESPONSE_BUFFER_SIZE];
			int len = 0;
			while ((len = contentStream.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}
			ret = outStream.toString();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		log.info("+++++++++++++++++++++++++++++" + targetURL);
		return ret;
	}
}
